<template>
  <Button icon="import" @click="onImport">导入</Button>
  <Modal
    title="导入"
    :open="visible"
    :width="1100"
    :mask-closable="false"
    :keyboard="false"
    centered
    @cancel="onClose"
  >
    <Steps v-model:current="current" :items="items" class="w-[800px] mx-auto" />
    <template v-if="current === 0">
      <template v-if="!rows.length">
        <p class="text-center py-5">
          <span>请下载表格模板，在填写完成后，点击导入文件，完成文件上传</span>
        </p>
        <Flex justify="center">
          <Upload
            :custom-request="customRequest"
            @change="onChange"
            :accept="accept"
            :before-upload="onBeforeUpload"
          >
            <div
              class="w-96 h-48 flex flex-col items-center justify-evenly rounded-sm border border-dashed"
            >
              <p class="text-center text-2xl">
                <CloudUploadOutlined
                  :style="{ color: colorPrimary, fontSize: '80px' }"
                ></CloudUploadOutlined>
              </p>
              <p class="ant-upload-text">
                <span>将文件拖到此处，或</span
                ><a :style="{ color: colorPrimary }">点击上传</a>
              </p>
            </div>
          </Upload>
        </Flex>
        <p class="text-center py-5">
          <span
            >仅允许导入 xls、xlsx 格式文件。<a
              @click="onDownload"
              :style="{ color: colorPrimary, cursor: 'pointer' }"
              >下载模板</a
            ></span
          >
        </p>
      </template>
      <ProTable
        v-else
        :height="500"
        :columns="columns"
        :fetch-list-api="fetchList"
        hide-pagination
        hide-search
      />
    </template>
    <template v-else>
      <Result status="success" title="导入成功"></Result>
    </template>

    <template #footer>
      <template v-if="current === 0 && rows.length">
        <AButton @click="rows = []">上一步</AButton>
        <AButton type="primary" @click="onConfirm" :loading="loading"
          >提交</AButton
        >
      </template>
      <template v-if="current === 1">
        <AButton @click="onClose">关闭</AButton>
      </template>
    </template>
  </Modal>
</template>
<script setup lang="tsx">
import { ref } from 'vue';
import {
  CheckOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
} from '@ant-design/icons-vue';
import {
  Button as AButton,
  Flex,
  Modal,
  Result,
  Steps,
  type StepsProps,
  Upload,
  type UploadProps,
  message,
  theme,
} from 'ant-design-vue';
import { AxiosRequestConfig } from 'axios';
import { useRequest } from 'vue-request';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import Button from '../Button/index';

defineOptions({
  name: 'ImportModal',
});

const emits = defineEmits<{
  downloadTemplate: [];
  closed: [];
}>();

interface Props {
  uploadApi: (data: FormData, config: AxiosRequestConfig) => Promise<any>;
  submitApi: (data: any) => Promise<any>;
  columns: ProTableProps['columns'];
  accept: UploadProps['accept'];
}

const props = defineProps<Props>();

const { defaultAlgorithm, defaultSeed } = theme;
const { colorPrimary } = defaultAlgorithm(defaultSeed);

const current = ref<number>(0);
const visible = ref<boolean>(false);
const onImport = () => {
  visible.value = true;
};

const items: StepsProps['items'] = [
  {
    title: '下载模板',
    icon: <CloudDownloadOutlined />,
    disabled: true,
  },
  {
    title: '导入成功',
    icon: <CheckOutlined />,
    disabled: true,
  },
];

const onClose = () => {
  visible.value = false;
  current.value = 0;
  rows.value = [];
  emits('closed');
};

const onDownload = () => {
  emits('downloadTemplate');
};

const rows = ref([]);
const fetchList = async (params: { pageSize: number; pageNum: number }) => {
  const { pageSize, pageNum } = params;
  const result = {
    rows: rows.value.slice((pageNum - 1) * pageSize, pageNum * pageSize),
    total: rows.value.length,
  };
  return result;
};

const { runAsync, loading } = useRequest(props.submitApi, { manual: true });

const onConfirm = async () => {
  await runAsync(rows.value);
  current.value = 1;
  // visible.value = false;
  // rows.value = [];
  // current.value = 0;
  // emits('closed');
};

const onChange: UploadProps['onChange'] = (info) => {
  const { file } = info;
  if (file.status === 'done') {
    rows.value = file.response as any;
  }
};

const onBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  if (!props.accept?.includes(file.name.split('.').pop() || '')) {
    message.error(`仅支持${props.accept}类型文件`);
    return false;
  }
  return true;
};

const customRequest: UploadProps['customRequest'] = ({
  file,
  filename,
  onError,
  onSuccess,
  onProgress,
}) => {
  const formData = new FormData();
  formData.append(filename || 'file', file);
  props
    .uploadApi(formData, {
      skipError: true,
      onUploadProgress: onProgress,
    })
    .then((res) => onSuccess?.(res.data))
    .catch((err) => {
      Modal.error({
        title: '提示',
        content: err.message,
      });
      onError?.(err);
    });
};
</script>
